#include "StarManager.h"
#include "global/GlobalPath.h"
#include "global/GlobalDefine.h"
#include "global/GlobalParam.h"
#include "util/PosLoadUtil/PosLoadUtil.h"
#include "enum/EnumPosType.h"
#include "entity/Entity/Star/Star.h"
#include "entity/Position/StarPos/StarPos.h"
#include "cocos2d.h"
#include "cocos-ext.h"
#include "CocoStudio/Reader/GUIReader.h"
#include "util/StarPollUtil/StarPollUtil.h"

USING_NS_CC;
USING_NS_CC_EXT;
using namespace cocos2d::ui;

StarManager::StarManager(){
	m_starPosList = NULL;
	m_starList = NULL;
}

StarManager::~StarManager(){
	CCObject* obj = NULL;
	Star* star = NULL;

	CCARRAY_FOREACH(m_starList,obj){
		star = dynamic_cast<Star*>(obj);
		StarPollUtil::shareStarPollUtil()->pushStarAndStop(star);
	}
	CC_SAFE_RELEASE(m_starPosList);
	CC_SAFE_RELEASE(m_starList);
	
	
}

StarManager* StarManager::createWithLevel(int level,int layerNum){
	StarManager* starManager = new StarManager();
	if(starManager && starManager->initWithLevel(level,layerNum)){
		starManager->autorelease();
	} else{
		CC_SAFE_DELETE(starManager);
		starManager = NULL;
	}
	return starManager;
}

bool StarManager::initWithLevel(int level,int layerNum){
	bool bRet = false;
	do{
		m_starPosList = CCArray::create();
		CC_SAFE_RETAIN(m_starPosList);

		m_starList = CCArray::create();
		CC_SAFE_RETAIN(m_starList);

		loadStarPosList(level);
		createStarByPosList(layerNum);

		bRet = true;
	}while(0);
	return bRet;
}

void StarManager::loadStarPosList(int level){
	CCString* starStr = CCString::createWithFormat(PATH_PLIST_TOLLGATE_starPos,level);

	CCArray* posList = PosLoadUtil::sharePosLoadUtil()->loadPosWithFile(starStr->getCString(),enStarPos,this,10,false);

	m_starPosList->addObjectsFromArray(posList);
}

void StarManager::createStarByPosList(int layerNum){
	
	CCObject* obj = NULL;
	StarPos* starPos = NULL;

	CCARRAY_FOREACH(m_starPosList,obj){
		starPos = dynamic_cast<StarPos*>(obj);
		if(starPos){
			Star* star = StarPollUtil::shareStarPollUtil()->popStarAndBegin();
			CCPoint starPoint = ccp(starPos->getPos().x,starPos->getPos().y + layerNum * SIZE_Y_bg);
			star->setPosition(starPoint);

			m_starList->addObject(star);
			this->addChild(star);
		}
	}
}

CCArray* StarManager::getStarList(){
	return m_starList;
}